/**
 * 邮件编辑器组件 - 可复用的邮件编写组件
 * 集成智能编辑器、变量面板、数据源选择等功能
 */
import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Form, Alert, message } from 'antd';
import SmartEditor from '@/components/SmartEditor';
import VariablePanel from '@/components/VariablePanel';
import DataSourceSelector from '@/components/DataSourceSelector';
import { request } from '@umijs/max';

interface Variable {
  name: string;
  display_name: string;
  field_type: string;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
  source_type: 'system' | 'data'; // 新增：区分系统变量和数据变量
}

interface DataSourceItem {
  id: number;
  name: string;
  type: string;
}

interface EmailContent {
  subject: string;
  content: string;
}

interface EmailComposerProps {
  value?: EmailContent;
  onChange?: (content: EmailContent) => void;
  showDataSourceSelector?: boolean;
  dataSources?: DataSourceItem[];
  onDataSourceChange?: (dataSource: DataSourceItem | null) => void;
  form?: any; // Ant Design Form 实例
  subjectRules?: any[];
  contentRules?: any[];
}

const EmailComposer: React.FC<EmailComposerProps> = ({
  value = { subject: '', content: '' },
  onChange,
  showDataSourceSelector = true,
  dataSources = [],
  onDataSourceChange,
  form,
  subjectRules = [{ required: true, message: '请输入邮件主题' }],
  contentRules = [{ required: true, message: '请输入邮件内容' }],
}) => {
  const [emailContent, setEmailContent] = useState<EmailContent>(value);
  const [selectedDataSource, setSelectedDataSource] = useState<DataSourceItem | null>(null);
  const [variables, setVariables] = useState<Variable[]>([]);
  const [focusedEditor, setFocusedEditor] = useState<'subject' | 'content'>('content');
  const [loading, setLoading] = useState(false);

  // 编辑器引用
  const subjectEditorRef = useRef<any>(null);
  const contentEditorRef = useRef<any>(null);

  // 同步外部值变化
  useEffect(() => {
    setEmailContent(value);
  }, [value]);

  // 获取数据源的所有字段
  const fetchDataSourceFields = async (dataSourceId: number) => {
    setLoading(true);
    try {
      // 首先获取表列表
      const tablesResponse = await request(`/api/data-sources/${dataSourceId}/tables`);
      const tables = tablesResponse.tables || [];
      
      if (tables.length === 0) {
        message.warning('该数据源没有可用的表');
        return;
      }

      // 获取所有表的字段
      const allFields: Variable[] = [];
      for (const table of tables) {
        try {
          const fieldsResponse = await request(
            `/api/data-sources/${dataSourceId}/tables/${table.name}/fields`,
            {
              method: 'GET',
              params: { identify_types: true },
            }
          );
          
          // 为字段添加表名前缀以避免重名，并标记为数据变量
          const tableFields = (fieldsResponse || []).map((field: any) => ({
            ...field,
            name: tables.length > 1 ? `${table.name}.${field.name}` : field.name,
            display_name: tables.length > 1 ? `${table.name}.${field.display_name || field.name}` : (field.display_name || field.name),
            description: field.description || `来自表: ${table.name}`,
            source_type: 'data' as const, // 标记为数据变量
          }));
          
          allFields.push(...tableFields);
        } catch (error) {
          console.warn(`获取表 ${table.name} 的字段失败:`, error);
        }
      }

      // 添加系统变量
      const systemVariables: Variable[] = [
        {
          name: 'current_date',
          display_name: '当前日期',
          field_type: 'string',
          is_email: false,
          is_name: false,
          sample_value: new Date().toLocaleDateString(),
          source_type: 'system',
        },
        {
          name: 'current_time',
          display_name: '当前时间',
          field_type: 'string',
          is_email: false,
          is_name: false,
          sample_value: new Date().toLocaleTimeString(),
          source_type: 'system',
        },
        {
          name: 'company_name',
          display_name: '公司名称',
          field_type: 'string',
          is_email: false,
          is_name: false,
          sample_value: '邮件统一发送平台',
          source_type: 'system',
        },
      ];

      const combinedVariables = [...systemVariables, ...allFields];
      setVariables(combinedVariables);
      message.success(`已加载 ${combinedVariables.length} 个变量（${systemVariables.length} 个系统变量，${allFields.length} 个数据变量）`);
    } catch (error: any) {
      message.error(error.message || '获取数据源字段失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理数据源选择
  const handleDataSourceChange = async (dataSourceId: number) => {
    const dataSource = dataSources.find(ds => ds.id === dataSourceId);
    if (dataSource) {
      setSelectedDataSource(dataSource);
      setVariables([]); // 清空之前的变量
      message.success(`已选择数据源: ${dataSource.name}`);
      
      // 获取数据源字段
      await fetchDataSourceFields(dataSourceId);
      
      // 通知父组件
      onDataSourceChange?.(dataSource);
    }
  };

  // 清除数据源选择
  const handleDataSourceClear = () => {
    setSelectedDataSource(null);
    setVariables([]);
    onDataSourceChange?.(null);
  };

  // 智能插入变量到当前焦点的编辑器
  const insertVariableToFocusedEditor = (variableName: string) => {
    const variable = variables.find(v => v.name === variableName);
    
    if (focusedEditor === 'subject') {
      const newSubject = emailContent.subject + `{{${variableName}}}`;
      const newContent = { ...emailContent, subject: newSubject };
      setEmailContent(newContent);
      form?.setFieldValue('subject', newSubject);
      onChange?.(newContent);
    } else {
      const newContentText = emailContent.content + `{{${variableName}}}`;
      const newContent = { ...emailContent, content: newContentText };
      setEmailContent(newContent);
      form?.setFieldValue('content', newContentText);
      onChange?.(newContent);
    }

    // 显示变量类型提示
    if (variable) {
      const typeText = variable.source_type === 'system' ? '系统变量' : '数据变量';
      message.success(`已插入${typeText}: {{${variableName}}}`);
    }
  };

  // 处理内容变化
  const handleContentChange = (field: 'subject' | 'content', value: string) => {
    const newContent = { ...emailContent, [field]: value };
    setEmailContent(newContent);
    form?.setFieldValue(field, value);
    onChange?.(newContent);
  };

  // 分析当前使用的变量类型
  const analyzeVariableUsage = () => {
    const usedVariables = variables.filter(variable => {
      const pattern = new RegExp(`\\{\\{${variable.name}\\}\\}`, 'g');
      return pattern.test(emailContent.subject) || pattern.test(emailContent.content);
    });

    const systemVars = usedVariables.filter(v => v.source_type === 'system');
    const dataVars = usedVariables.filter(v => v.source_type === 'data');

    return { systemVars, dataVars, usedVariables };
  };

  const { systemVars, dataVars } = analyzeVariableUsage();

  return (
    <Row gutter={16}>
      <Col span={16}>
        {/* 数据源选择器 */}
        {showDataSourceSelector && (
          <DataSourceSelector
            dataSources={dataSources}
            selectedDataSource={selectedDataSource}
            onDataSourceChange={handleDataSourceChange}
            onDataSourceClear={handleDataSourceClear}
            loading={loading}
          />
        )}

        {/* 邮件主题 */}
        <Form.Item
          label="邮件主题"
          name="subject"
          rules={subjectRules}
        >
          <div onFocus={() => setFocusedEditor('subject')}>
            <SmartEditor
              ref={subjectEditorRef}
              value={emailContent.subject}
              onChange={(value) => handleContentChange('subject', value)}
              placeholder="输入邮件主题，使用 {{变量名}} 插入动态数据"
              variables={variables}
              rows={2}
            />
          </div>
        </Form.Item>

        {/* 邮件内容 */}
        <Form.Item
          label="邮件内容"
          name="content"
          rules={contentRules}
        >
          <div onFocus={() => setFocusedEditor('content')}>
            <SmartEditor
              ref={contentEditorRef}
              value={emailContent.content}
              onChange={(value) => handleContentChange('content', value)}
              placeholder="输入邮件内容，使用 {{变量名}} 插入动态数据"
              variables={variables}
              rows={12}
            />
          </div>
        </Form.Item>

        {/* 变量使用分析 */}
        {(systemVars.length > 0 || dataVars.length > 0) && (
          <Alert
            message="变量使用分析"
            description={
              <div>
                {systemVars.length > 0 && <div>系统变量 {systemVars.length} 个：适合批量发送</div>}
                {dataVars.length > 0 && <div>数据变量 {dataVars.length} 个：适合个性化发送</div>}
                <div style={{ marginTop: 4, fontSize: '12px', color: '#666' }}>
                  建议发送模式：{dataVars.length > 0 ? '个性化发送' : '批量发送'}
                </div>
              </div>
            }
            type="info"
            size="small"
            style={{ marginBottom: 16 }}
          />
        )}
      </Col>

      <Col span={8}>
        {/* 数据源选择提示 */}
        {!selectedDataSource && showDataSourceSelector && (
          <Alert
            message="选择数据源以获取可用变量"
            description="选择数据源后，这里将显示可用的变量字段"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 变量面板 */}
        <VariablePanel
          variables={variables}
          onVariableClick={insertVariableToFocusedEditor}
          title={selectedDataSource ? `${selectedDataSource.name} - 可用变量` : "可用变量"}
          loading={loading}
        />

        {/* 焦点提示 */}
        {variables.length > 0 && (
          <Alert
            message={`当前焦点：${focusedEditor === 'subject' ? '邮件主题' : '邮件内容'}`}
            description="点击变量将插入到当前焦点的输入框中"
            type="info"
            size="small"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Col>
    </Row>
  );
};

export default EmailComposer;
